﻿using UnityEngine;
using UnityEditor;
using System.IO;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

public class ScenesWindow : EditorWindow
{
	public string scenesInfoPath = "Assets/Resources/Data/Scenes.asset";
	private SceneInfo sceneInfo;

	private List<SceneInfo.Info> items;
	
	[MenuItem("Paperclips/Data/Scenes...")]
	private static void Init()
	{
		EditorWindow.GetWindow<ScenesWindow>("Scenes");
	}
	
	public void OnFocus()
	{
		sceneInfo = CreateAsset<SceneInfo>(scenesInfoPath);

		string[] allScenes = System.Enum.GetNames(typeof(SceneID));
		foreach (string scene in allScenes)
		{
			bool contains = false;
			sceneInfo.scenesInfos.FirstOrDefault(x => { if (x.id.ToString().Equals(scene)) { contains = true; return true; } else { return false; } });
			if (!contains)
			{
				sceneInfo.scenesInfos.Add(new SceneInfo.Info(scene));
			}
		}

		sceneInfo.scenesInfos = sceneInfo.scenesInfos.OrderBy(x => x.id.ToString()).ToList();
	}

	private T CreateAsset<T>(string _path) where T : ScriptableObject
	{
		string folder = _path.Remove(_path.LastIndexOf("/"));
		if (!Directory.Exists(folder))
		{
			Directory.CreateDirectory(folder);
			AssetDatabase.Refresh();
		}

		T asset = (T)AssetDatabase.LoadAssetAtPath(_path, typeof(T));
		if (asset == null)
		{
			asset = ScriptableObject.CreateInstance<T>();
			AssetDatabase.CreateAsset(asset, _path);
			AssetDatabase.SaveAssets();
			AssetDatabase.Refresh();

		}
		
		return asset;
	}

	private void OnGUI()
	{
		foreach (SceneInfo.Info info in sceneInfo.scenesInfos)
		{
			DrawItem(info);
		}
	}

	private void DrawItem(SceneInfo.Info _info)
	{
		EditorGUILayout.BeginHorizontal("box");
		{
			EditorGUILayout.LabelField(_info.id.ToString());
			_info.name = EditorGUILayout.TextField(_info.name);
			_info.type = (SceneInfo.Info.Type)EditorGUILayout.EnumPopup(_info.type);
		}
		EditorGUILayout.EndHorizontal();
	}
}
